package cn.xc.user.service.impl;


import cn.xc.basic.constant.VerifyCodeConstant;
import cn.xc.basic.service.impl.BaseServiceImpl;
import cn.xc.basic.util.AjaxResult;
import cn.xc.basic.util.HttpUtil;
import cn.xc.basic.util.Md5Utils;
import cn.xc.basic.util.StrUtils;
import cn.xc.org.exception.BusinessException;
import cn.xc.system.domain.Menu;
import cn.xc.system.mapper.MenuMapper;
import cn.xc.system.mapper.PermissionMapper;
import cn.xc.user.Constants.WxConstants;
import cn.xc.user.domain.LoginData;
import cn.xc.user.domain.Logininfo;
import cn.xc.user.domain.User;
import cn.xc.user.domain.Wxuser;
import cn.xc.user.dto.BinderDto;
import cn.xc.user.dto.LoginDto;
import cn.xc.user.jwt.JwtUtils;
import cn.xc.user.jwt.RsaUtils;
import cn.xc.user.mapper.LogininfoMapper;
import cn.xc.user.mapper.UserMapper;
import cn.xc.user.mapper.WxuserMapper;
import cn.xc.user.service.ILogininfoService;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.security.PrivateKey;
import java.security.PublicKey;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;


/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    /**
     * 賬號登錄
     * @param loginDto
     * @return
     */
    @Override
    public AjaxResult account(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String checkPass = loginDto.getCheckPass();
        Integer loginType = loginDto.getType();

        //1.校驗空值
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(checkPass)) {
            throw new BusinessException("用戶和密碼不能為空!!");
        }
        //2.校驗用戶和密碼
        Logininfo logininfo = logininfoMapper.LoadByaccount(loginDto);
        if (logininfo == null) {
            throw new BusinessException("請輸入正確的用戶和密碼!!!");
        }
        //3.校驗密碼
        String dbpass = logininfo.getPassword();
        String byMd5 = Md5Utils.encrypByMd5(checkPass + logininfo.getSalt());
        if (!dbpass.equals(byMd5)) {
            throw new BusinessException("密碼錯誤!");
        }

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        //6.響應數據
        return AjaxResult.me().setResultObj(map);
    }

    /**
     * 微信登錄
     * @param code
     * @return
     */
    @Override
    public AjaxResult wechatLogin(String code) {
        //1.根據code發送請求獲取token和openid
        String url = WxConstants.GET_ACK_URL
                .replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        String jsonStr = HttpUtil.httpGet(url);

        //2.將響應的json字符串  轉成 json對象
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String access_token = jsonObject.getString("access_token");
        String openid = jsonObject.getString("openid");

        //3.通過openid去t_wxuser中查詢
        Wxuser wxuser = wxuserMapper.loadByOpenid(openid);

        if (wxuser != null && wxuser.getUserId() != null) {//如果綁定了
            //4.有 綁定過 - 直接免密登錄【獲取logininfo對象 登錄】
            Logininfo logininfo = logininfoMapper.loadLogininfoByUserId(wxuser.getUserId());

            Map<String, Object> map = loginSuccessJwtHandler(logininfo);

            //響應數據
            return AjaxResult.me().setResultObj(map);
        } else {
            //5.沒有 - 需要跳轉頁面綁定 - 響應給前端進行跳轉
            HashMap<String, Object> map = new HashMap<>();
            map.put("access_token", access_token);
            map.put("openid", openid);
            return AjaxResult.me().setSuccess(false).setResultObj(map);
        }
    }

    @Override
    public AjaxResult wechatBinder(BinderDto binderDto) {
        String phone = binderDto.getPhone();
        String verifyCode = binderDto.getVerifyCode();
        String accesstoken = binderDto.getAccessToken();
        String openId = binderDto.getOpenid();
        //校验
        //1.校验 - 空置校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("数据不能为空");
        }
        //2.校验 - 验证码是否过期  //code:1215215155
        Object redisCode = redisTemplate.opsForValue().get(VerifyCodeConstant.BINDER_CODE_PREFIX + phone);
        if (redisCode == null) {
            throw new BusinessException("验证码过期");
        }
        //3.校验 - 验证码是否正确
        if (!redisCode.toString().split(":")[0].equalsIgnoreCase(verifyCode.trim())) {
            throw new BusinessException("验证码错误");
        }
        //绑定用户：t_wxUser【user_id】 绑定 t_user
        //4.获取WxUser - 发送第三个请求 - json字符串
        String url = WxConstants.GET_USER_URL
                .replace("ACCESS_TOKEN", accesstoken)
                .replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);
        //5.通过phone查询User
        User user = userMapper.loadByPhone(phone);
        //5.1.如果没有 - 根据phone创建User对象 - 创建Logininfo对象 - 保存Logininfo对象 - 保存User对象
        if (user == null) {
            user = phone2User(phone);
            Logininfo logininfoTmp = user2Logininfo(user);
            logininfoMapper.save(logininfoTmp);
            user.setLogininfoId(logininfoTmp.getId());
            userMapper.save(user);
        }
        //6.将User对象的id设置到WxUser对象中
        wxuser.setUserId(user.getId());
        //7.将WxUser对象添加到数据库
        wxuserMapper.save(wxuser);


        //8.做免密登录
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);

        return AjaxResult.me().setResultObj(map);
    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机的纯数据密码
        String randomPwd = StrUtils.getRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        Wxuser wxuser = new Wxuser();
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setAddress(jsonObject.getString("country") + jsonObject.getString("province") + jsonObject.getString("city"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));
        return wxuser;
    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        try {
            Map<String,Object> map = new HashMap<>();
            //细节：如果是管理员才需要加四个数据，如果是用户只需要：登录信息对象，jwt串【1,4】
            //一：想办法获取四个数据
            //1.登录信息对象 - 在参数中
            map.put("logininfo",logininfo);
            LoginData loginData = new LoginData();
            loginData.setLogininfo(logininfo);
            if (logininfo.getType() == 0) {//后台管理员
                //2.当前登录人的所有权限的sn集合 - 昨天写过了 - 直接调用方法
                List<String> permissions = permissionMapper.loadPermissionSnByLogininfoId(logininfo.getId());
                map.put("permissions", permissions);
                loginData.setPermissions(permissions);
                //3.当前登录人的所有二级菜单及其它的父级菜单【前端需要】 - 自己写 - 难点1
                List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
                map.put("menus", menus);
                loginData.setMenus(menus);
            }
            //4.将以上三个数据装到LoginData  - 使用工具类进行加密【1 2】 - jwt串
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);//没有做刷新过期时间
            map.put("token", jwtToken);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


}